<?php


namespace app\index\controller\xilujob;


use app\admin\model\xilujob\EducationLevel;
use app\admin\model\xilujob\Salary;
use app\admin\model\xilujob\WorkExperience;
use app\common\controller\xilujob\Xilujob;
use app\common\library\Email;
use app\common\model\xilujob\Area;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\ResumeActionLog;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\ResumeViewLog;
use app\common\model\xilujob\UserCollection;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\Exception;

class Resume extends Xilujob
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\xilujob\Resume();
    }

    /**
     * 人才推荐 - 企业用户
     */
    public function index() {

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            #先找到项目对应的用户
            $sub = Job::alias('job')
                ->field('job.*,jobIntention.resume_id,jobIntention.job_type,jobIntention.fav_category_id,jobIntention.expect_salary_id,jobIntention.previous_job_category_id,jobIntention.fav_province_id,jobIntention.fav_city_id,salary.name salary_name,area.allname')
                ->join(config('database.prefix').'xilujob_job_location jobLocation','job.id=jobLocation.job_id','INNER')
                ->join(config('database.prefix').'xilujob_resume_job_intention jobIntention','jobIntention.fav_category_id=job.job_category_id AND jobIntention.job_type = job.type AND jobIntention.fav_city_id=jobLocation.city_id','INNER')
                ->join(config('database.prefix').'xilujob_salary salary','salary.id=jobIntention.expect_salary_id','INNER')
                ->join(config('database.prefix').'xilujob_area area','area.id=jobIntention.fav_city_id','INNER')
                ->where($where)
                //->group('jobIntention.resume_id')
                ->buildSql();

            $companyId = $this->company->id;
            $where2 = [];
            if($companyId) {
                $where2['resume.user_id'] = ['not in',function($query) use($companyId) {
                    $query->name('xilujob_user_blacklist_company')->where('company_id',$companyId)->field('user_id');
                }];
            }
            $resumes = $this->model
                ->alias('resume')
                ->field('resume.*,sub.resume_id,sub.job_type,sub.fav_category_id,sub.expect_salary_id,sub.previous_job_category_id,sub.fav_province_id,sub.fav_city_id,sub.salary_name,sub.allname,personal.avatar,personal.birthdate,personal.realname,personal.work_experience_id,personal.education_level_id,personal.current_state_id')
                ->with(['summary','works'])
                ->join($sub.' sub','resume.id=sub.resume_id','INNER')
                //->join(config('database.prefix').'user user','resume.user_id=user.id','INNER')
                ->join(config('database.prefix').'xilujob_resume_personal_info personal','resume.id=personal.resume_id','INNER')
                ->where('resume.status', 1)
                ->where('resume.black', 0)
                ->where('resume.complete_percent','>', 0)
                ->where($where2)
                ->order('resume.refresh_date','desc')
                ->order('resume.updatetime','desc')
                ->paginate($limit);
            foreach ($resumes as $resume){
                $resume['work_experience_name'] = \app\common\model\xilujob\WorkExperience::getnameById($resume->work_experience_id);
                $resume['education_level_name'] = \app\common\model\xilujob\EducationLevel::getnameById($resume->education_level_id);
                $resume['current_state_name'] = \app\common\model\xilujob\WorkState::getnameById($resume->current_state_id);
                $resume['age'] = !$resume->birthdate?'':floor((strtotime(date('Y-m-d')) - strtotime($resume->birthdate))/86400/365);
            }

            $result = array("total" => $resumes->total(), "rows" => $resumes->items());

            return json($result);
        }

        $this->assignconfig('jobs', Job::where('publisher_id',$this->company->id)->column('id,job_name as name'));
        $this->assignconfig('education_level',EducationLevel::order('weigh','asc')->column('id,name'));
        $this->assignconfig('expect_salary',Salary::where('option_type',3)->order('min','asc')->column('id,name'));
        $this->assignconfig('work_experience',WorkExperience::order('weigh','asc')->column('id,name'));
        $this->view->assign('title', '推荐简历');
        return $this->view->fetch();
    }

    /**
     * 简历库
     */
    public function resumes() {


        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            #先找到项目对应的用户
            $sub = Job::alias('job')
                ->field('job.*,jobIntention.resume_id,jobIntention.job_type,jobIntention.fav_category_id,jobIntention.expect_salary_id,jobIntention.previous_job_category_id,jobIntention.fav_province_id,jobIntention.fav_city_id,salary.name salary_name,area.allname')
                ->join(config('database.prefix').'xilujob_job_location jobLocation','job.id=jobLocation.job_id','INNER')
                ->join(config('database.prefix').'xilujob_resume_job_intention jobIntention','jobIntention.fav_category_id=job.job_category_id AND jobIntention.job_type = job.type AND jobIntention.fav_city_id=jobLocation.city_id','INNER')
                ->join(config('database.prefix').'xilujob_salary salary','salary.id=jobIntention.expect_salary_id','INNER')
                ->join(config('database.prefix').'xilujob_area area','area.id=jobIntention.fav_city_id','INNER')
                ->where($where)
                //->group('jobIntention.resume_id')
                ->buildSql();
            $where2['resume.status'] = 1;
            $where2['resume.black'] = 0;
            $where2['resume.complete_percent'] = ['>',0];
            $companyId = $this->company->id;
            if($companyId) {
                $where2['resume.user_id'] = ['not in',function($query) use($companyId) {
                    $query->name('xilujob_user_blacklist_company')->where('company_id',$companyId)->field('user_id');
                }];
            }

            list($where3, $sort, $order, $offset, $limit) = $this->buildparams2();
            $lists = $this->model
                ->alias('resume')
                ->join($sub.' sub','resume.id=sub.resume_id','INNER')
                ->with(['summary','works'])
                ->field('resume.id,resume.user_id,resume.top,resume.updatetime,sub.resume_id,sub.job_type,sub.salary_name,sub.allname,personal.avatar,personal.birthdate,personal.realname,personal.work_experience_id,personal.education_level_id,personal.current_state_id')
                //->join(config('database.prefix').'user user','resume.user_id=user.id','INNER')
                ->join(config('database.prefix').'xilujob_resume_personal_info personal','resume.id=personal.resume_id','INNER')
                ->where($where2)
                ->where($where3)
                ->order('resume.top','desc')
                ->order('resume.refresh_date','desc')
                ->order('resume.complete_percent','desc')
                ->order('resume.updatetime','desc')
                ->paginate($limit);
            foreach ($lists as $resume){
                $resume['work_experience_name'] = \app\common\model\xilujob\WorkExperience::getnameById($resume->work_experience_id);
                $resume['education_level_name'] = \app\common\model\xilujob\EducationLevel::getnameById($resume->education_level_id);
                $resume['current_state_name'] = \app\common\model\xilujob\WorkState::getnameById($resume->current_state_id);
                $resume['age'] = !$resume->birthdate?'':floor((strtotime(date('Y-m-d')) - strtotime($resume->birthdate))/86400/365);
            }

            $result = array("total" => $lists->total(), "rows" => $lists->items());

            return json($result);

        }
        $this->assignconfig('jobs', Job::where('publisher_id',$this->company->id)->column('id,job_name as name'));
        $this->assignconfig('education_level',EducationLevel::order('weigh','asc')->column('id,name'));
        $this->assignconfig('expect_salary',Salary::where('option_type',3)->order('min','asc')->column('id,name'));
        $this->assignconfig('work_experience',WorkExperience::order('weigh','asc')->column('id,name'));
        $this->view->assign('title','简历库');
        return $this->view->fetch();
    }


    public function detail($ids) {
        $resume = \app\common\model\xilujob\Resume::getResume($ids,true);
        if(!$resume) {
            $this->error(__('no record'));
        }
        $hasActionLog = ResumeActionLog::hasLog($this->company->id,$resume->user_id,$resume->id);
        if(get_addon_config('xilujob')['hide_contact'] && !$hasActionLog) {
            $resume->personal->mobile = substr($resume->personal->mobile,0,3).'********';
            $resume->personal->email = $resume->personal->email?'**********':'';
        }else {
            $resume->personal->hide_mobile = 0;
        }

        $isFav = UserCollection::isFav($this->company->id, $resume->id,UserCollection::TYPE_RESUME);

        $isInterviewing = \app\common\model\xilujob\JobInterview::isInterviewing($resume->user_id, $this->company->id);

       // $similarResumes = \app\common\model\xilujob\Resume::getSimilarResumes($ids, [],$this->company->id);

        try {
            ResumeViewLog::viewResume($this->company->id, $ids);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->assign('title','人才详情');
        $this->assign('has_action_log', $hasActionLog);
        $this->assignconfig('apply_id',$this->request->param('apply_id',0));
        return $this->fetch('', [
            'resume'=>$resume, 'is_fav'=>$isFav, 'is_interviewing'=>$isInterviewing
        ]);
    }

    //收藏简历
    public function toggle_fav() {
        $resumeId = $this->request->post('id');
        $result = UserCollection::toggleFav($this->company->id, $resumeId, UserCollection::TYPE_RESUME);
        $this->success('','',['is_fav'=>$result]);
    }

    /**
     * 下载简历
     * @param $ids
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function download($ids) {
        $this->layout = '';
        $xilujobuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xilujobuser->enterprise_model->audit_status!=1) {
            $this->error('企业审核通过后方可下载简历');
        }
        $this->assign('host', $this->request->domain());
        $resume = \app\common\model\xilujob\Resume::getResume($ids,true);
        $this->assign('resume',$resume);
        if(!$resume) {
            $this->error(__('no record'));
        }
        //判断是否有权限下载
        try {
            $result = ResumeActionLog::record($this->company->id, $resume->user_id, $resume->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        //记录下载
        ResumeDownload::downloadResume($this->company->id, $resume);

        $type = $this->request->param('type');

        function encodeFileName($filename) {
            //处理中文文件名
            $ua = $_SERVER["HTTP_USER_AGENT"];
            $encoded_filename = rawurlencode($filename);
            if (preg_match("/(MSIE)|(Trident)|(Edge)/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $filename . '"');
            }
        }
        $fileName = sprintf('西陆+%s+%s', $resume->personal->realname,$resume->id);
        if($type==='html') {
            $html = $this->fetch('export_word');
            $fileName = ($fileName . '.html');
            header("Content-Type:application/octet-stream;charset=utf-8");
            encodeFileName($fileName);
            return $html;
        }else {
            $html = $this->fetch('export_word');
            $fileName = ($fileName . '.doc');
            header("Content-Type:application/octet-stream;charset=utf-8");
            encodeFileName($fileName);
            return $html;
        }
    }
    
    public function batch_download() {
        $ids = $this->request->param('ids');
        $ids = $ids ? explode(',', $ids) : [];
        if(!$ids) {
            $this->error('');
        }

        function encodeFileName($filename) {
            //处理中文文件名
            $ua = $_SERVER["HTTP_USER_AGENT"];
            $encoded_filename = rawurlencode($filename);
            if (preg_match("/(MSIE)|(Trident)|(Edge)/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $filename . '"');
            }
        }

        $this->layout = '';
        Db::startTrans();
        try {
            $this->assign('host', request()->domain());

            $zip = new \ZipArchive();
            $zipFile = tempnam(sys_get_temp_dir(),'resume_zip_');
            $r = $zip->open($zipFile,\ZipArchive::CREATE | \ZipArchive::OVERWRITE);
            foreach($ids as $id) {
                $resume = \app\common\model\xilujob\Resume::getResume($id,true);
                $this->assign('resume',$resume);
                if(!$resume) {
                    $this->error(__('no record'));
                }
                try {
                    $result = ResumeActionLog::record($this->company->id, $resume->user_id, $resume->id);
                }catch (Exception $e){
                    $this->error($e->getMessage());
                }
                //记录下载
                ResumeDownload::downloadResume($this->company->id, $resume);

                $type = $this->request->param('type');

                $fileName = sprintf('西陆+%s+%s', $resume->personal->realname,$resume->id);
                if($type==='html') {
                    $html = $this->fetch('export_word');
                    $fileName = ($fileName . '.html');
//                    header("Content-Type:application/octet-stream;charset=utf-8");
//                    encodeFileName($fileName);
                }else {
                    $html = $this->fetch('export_word');
                    $fileName = ($fileName . '.doc');
                }
                $zip->addFromString($fileName, $html);
            }
            $zip->close();
            header("Content-Type:application/octet-stream;charset=utf-8");
            encodeFileName('简历.zip');
            Db::commit();
            return file_get_contents($zipFile);
        }catch (\Exception $e) {
            halt($e->getMessage());
            $this->error($e->getMessage());
        }
    }
    //省份
    public function cxselect(){
        $type = $this->request->param('type');
        if($type == 'province'){
            $list = Area::where('level',1)->where('pid',0)->field('id as value,shortname as name')->select();
        }else if($type == 'city'){
            $pid = $this->request->param('province_id');
            $list = $list = Area::where('level',2)->where('pid',$pid)->field('id as value,shortname as name')->select();
        }


        $this->success('','',$list);
    }


    //分类三级联动
    public function cxselect2(){
        $type = $this->request->param('type');
        if($type == 'category_one'){
            $list = \app\admin\model\xilujob\JobCategory::field('id as value,category_name as name')->select();
        }else if($type == 'category_two'){
            $pid = $this->request->param('category_one');
            $list = $list = \app\admin\model\xilujob\JobCategory::where('pid',$pid)->field('id as value,category_name as name')->select();
        }else if($type == 'category_three'){
            $pid = $this->request->param('category_two');
            $list = $list = \app\admin\model\xilujob\JobCategory::where('pid',$pid)->field('id as value,category_name as name')->select();
        }


        $this->success('','',$list);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }
        $where[0] = ['job.id','=',0];

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $arrSearch = [];
            foreach (explode(" ", $search) as $ko) {
                $arrSearch[] = '%'.$ko.'%';
            }
            $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
        }

        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            if($k == 'job.id'){
                $where[0] = ['job.id','=',$v];
                continue;
            } else if($k == 'jobIntention.fav_city_id'){
                $where[] = ['jobIntention.fav_city_id','=',$v];
                continue;
            }else{
                continue;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        // dump($where);exit;
        return [$where, $sort, $order, $offset, $limit,$page];
    }


    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams2($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $arrSearch = [];
            foreach (explode(" ", $search) as $ko) {
                $arrSearch[] = '%'.$ko.'%';
            }
            $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
        }
        $job_id_flag = false;
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }

            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            if($k == 'job.id'){
                $job_id_flag = true;
                continue;
            } elseif ($k == 'jobIntention.fav_city_id'){
                continue;
            }else if($k == 'age') {
                //年龄
                $age = explode(',',$v);
                $ageMin = $age[0];
                $ageMax = $age[1];

                if($ageMin){
                    $ageMaxWhere = (date('Y')-$ageMin).'-'.date('m-d');
                    $where[] = ['personal.birthdate','<=',$ageMaxWhere];
                }

                if($ageMax){
                    $ageMinWhere = (date('Y')-$ageMax).'-'.date('m-d');
                    $where[] = ['personal.birthdate','>=',$ageMinWhere];
                }
                continue;
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        if($where && !$job_id_flag) $this->error('请先选择具体职位');
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        // dump($where);exit;
        return [$where, $sort, $order, $offset, $limit,$page];
    }

}